package com.example.springboot.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.Mapper.FileMapper;
import com.example.springboot.common.Result;
import com.example.springboot.pojo.Files;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${files.upload.path}")
   private String filesuploadpath;
    @Resource
    private FileMapper fileMapper;

    @PostMapping("/update")
    public int update(@RequestBody Files files){
        //return spUserMapper.in(spUser);
        return fileMapper.updateById(files);//plus
    }

    //数据库里面:0表示false,1表示true
    @DeleteMapping("/{id}")
    public int delete(@PathVariable Integer id){
        Files files=fileMapper.selectById(id);
        files.setIsDelete(true);
        return fileMapper.updateById(files);
    }

    @PostMapping("/deleteAll")
    public boolean deleteAll(@RequestBody List<Integer> ids){
       List<Files> files=fileMapper.selectBatchIds(ids);
        for (Files f:files) {
            f.setIsDelete(true);
            fileMapper.updateById(f);//plus
        }
        return true;


    }


    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String filename=file.getOriginalFilename();
        String filetype=FileUtil.extName(filename);
        long filesize=file.getSize();

        //存盘里
        File uploadparentfile=new File(filesuploadpath);
        //存在？
        if(!uploadparentfile.exists()){
            uploadparentfile.mkdirs();
        }
        //标识码
        String uuid= IdUtil.fastSimpleUUID();
        String fileuuid=uuid+StrUtil.DOT+filetype;
        File uploadfile=new File(filesuploadpath+fileuuid);
        //文件存磁盘
        file.transferTo(uploadfile);
        String url="http://localhost:9090/file/"+fileuuid;
        //数据库
        Files save=new Files();
        save.setName(filename);
        save.setType(filetype);
        save.setSize(filesize/1024);
        save.setUrl(url);
        fileMapper.insert(save);
        return url;
    }

    @GetMapping("/{fileuuid}")
        public void download(@PathVariable String fileuuid, HttpServletResponse response)throws IOException{
        File uploadfile=new File(filesuploadpath+fileuuid);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileuuid, "UTF-8"));
        response.setContentType("application/octet-stream");

        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadfile));
        os.flush();
        os.close();

        }

    @GetMapping("/page")
    public IPage<Files> Page(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                              @RequestParam(defaultValue = "") String name){


        QueryWrapper<Files> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        queryWrapper.eq("is_delete", false);
        if(!"".equals(name)){queryWrapper.like("name",name);}
        IPage<Files> page=new Page<>(pageNum,pageSize);
      return   fileMapper.selectPage(page,queryWrapper);

    }

    @PostMapping("/uploadImg")
    public Object uploadImg(@RequestParam MultipartFile file) throws IOException {
        String filename=file.getOriginalFilename();
        String filetype=FileUtil.extName(filename);
        long filesize=file.getSize();

        //存盘里
        File uploadparentfile=new File(filesuploadpath);
        //存在？
        if(!uploadparentfile.exists()){
            uploadparentfile.mkdirs();
        }
        //标识码
        String uuid= IdUtil.fastSimpleUUID();
        String fileuuid=uuid+StrUtil.DOT+filetype;
        File uploadfile=new File(filesuploadpath+fileuuid);
        //文件存磁盘
        file.transferTo(uploadfile);
        String url="http://localhost:9090/file/"+fileuuid;
        //数据库
        Files save=new Files();
        save.setName(filename);
        save.setType(filetype);
        save.setSize(filesize/1024);
        save.setUrl(url);
        fileMapper.insert(save);

        return JSONUtil.parseObj("{\"errno\":0, \"data\":[{\"url\":\""+url+"\"}]}");
    }

}
